import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Inject 
} from '@nestjs/common';
import { PodsService } from './pods.service';
import { ResponseUtil } from '../common/utils/response.util';
import { NodeService } from '../node/node.service'; 
@Controller('pod')
export class PodsController {
  constructor(private readonly podsService: PodsService) {}
  @Inject(NodeService)
  private readonly NodeService:NodeService;

  //根据命名空间查询容器组列表
  public podsList: any = {
    list: [
      {
        namespace: 'karmada-system',
        name: 'karmada-scheduler-55d9649d6c-zgxwl',
        status: 'Running',
        podsIp: '10.240.0.205',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-scheduler',
            image:
              '32a221ca57de57facc9623ca994adc6fef6f1718c12a8530f533e6a549d57adf',
            ready: true,
            restartCount: 1,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:50Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-webhook-67f6f4db8-rf8pm',
        status: 'Running',
        podsIp: '10.240.0.207',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-webhook',
            image:
              '73f221dfd3ccd03b84e2f14819a1e87c2ee3f3f84a25d59af674db8806e94337',
            ready: true,
            restartCount: 1,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:54Z',
      },
      {
        namespace: 'karmada-system',
        name: 'etcd-0',
        status: 'Running',
        podsIp: '10.240.0.203',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'etcd',
            image:
              '9cdd6470f48c8b127530b7ce6ea4b3524137984481e48bcde619735890840ace',
            ready: true,
            restartCount: 1,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:09Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-dashboard-web-7f9454d85b-zg4wc',
        status: 'Running',
        podsIp: '10.240.0.206',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-dashboard-web',
            image:
              'd9a1d270bd0b25f3ce80f67d01e3536fe13b28d8107b1038c97394f8138b80d6',
            ready: true,
            restartCount: 1,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0.250',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-26T01:41:01Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-apiserver-56d6cfc4c8-j49cx',
        status: 'Running',
        podsIp: '10.240.0.202',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-apiserver',
            image:
              '8e49cdf98f4d1bb02b6ffdd753e549173bba453d3d476f03034be2ff8b928f43',
            ready: true,
            restartCount: 2,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:11Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-controller-manager-6cdf99bbb7-vnjw6',
        status: 'Running',
        podsIp: '10.240.0.204',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-controller-manager',
            image:
              '19e651a170d24114e8a1d657a831bcf2ab8be81c995e4bfa073ceaa98b58623e',
            ready: true,
            restartCount: 4,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:52Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-aggregated-apiserver-687844c474-bf6rt',
        status: 'Running',
        podsIp: '10.240.0.201',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-aggregated-apiserver',
            image:
              '75768cdd23560618f0fec2cb22d11bf193e653059529b5deded705fb98bc5bb3',
            ready: true,
            restartCount: 4,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0.100',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:43Z',
      },
      {
        namespace: 'karmada-system',
        name: 'kube-controller-manager-58b95ccc77-xxdlf',
        status: 'Running',
        podsIp: '10.240.0.200',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'kube-controller-manager',
            image:
              '82966213177587406113dba7f0f5bd4181f9a47d74cf09953bf43cb521efd0f5',
            ready: true,
            restartCount: 4,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-25T09:08:47Z',
      },
      {
        namespace: 'karmada-system',
        name: 'karmada-dashboard-api-6f94c69bf6-vcmqq',
        status: 'Running',
        podsIp: '10.240.0.214',
        nodeName: 'federation02',
        nodeIp: '192.168.8.30',
        containerStatuses: [
          {
            name: 'karmada-dashboard-api',
            image:
              '31ad48722a0bc640af6027b098185170c640831ec9e01ab4f3b53b5910994f87',
            ready: true,
            restartCount: 4,
            state: 'Running',
            reason: null,
            message: null,
          },
        ],
        cpuReq: '0.250',
        cpuLimit: '0',
        memoryReq: '0',
        memoryLimit: '0',
        createTime: '2025-08-26T01:44:45Z',
      },
    ],
    continueToken: null,
  };
  @Post('/listPodsByNamespace/:agentId')
  postListPodsByNamespace(@Body() body: any) {
    return ResponseUtil.success(this.podsList, '查询成功');
  }

  // 根据pod名称查询pod详情
  public podDetail: any = {
    namespace: 'karmada-system',
    name: 'karmada-scheduler-55d9649d6c-zgxwl',
    status: 'Running',
    nodeName: 'federation02',
    nodeIp: '192.168.8.30',
    podsIp: '10.240.0.205',
    scheduledTime: '2025-08-25 17:08:50',
    initializedTime: '2025-08-25 17:08:50',
    containersReadyTime: '2025-08-28 09:45:17',
    podReadyTime: '2025-08-28 09:45:17',
    containerStatuses: [
      {
        name: 'karmada-scheduler',
        image:
          '32a221ca57de57facc9623ca994adc6fef6f1718c12a8530f533e6a549d57adf',
        ready: true,
        restartCount: 1,
        state: 'Running',
        reason: null,
        message: null,
      },
    ],
  };
  @Post('/podDetail/:agentId')
  postGetPodDetail(@Body() body: any) {
    return ResponseUtil.success(this.podDetail, '查询成功');
  }

  // 获取pod事件列表
  public podEvents: any =[{
    reason: "Scheduled",
    time: "2025-09-02T08:30:15Z",
    count: 1,
    message: "Successfully assigned karmada-system/etcd-0 to federation02"
  },
  {
    reason: "Pulling",
    time: "2025-09-02T08:30:20Z",
    count: 1,
    message: "Pulling image 'k8s.gcr.io/etcd:3.5.0'"
  },
  {
    reason: "Pulled",
    time: "2025-09-02T08:30:45Z",
    count: 1,
    message: "Successfully pulled image 'k8s.gcr.io/etcd:3.5.0' in 25.324s"
  },];
  @Post('/podEvents/:agentId')
  postPodEvents(@Body() body: any) {
    return ResponseUtil.success(this.podEvents, '查询成功');
  }


  setPodMetrics(){
    return {
      cpu: (Math.random() * 100).toFixed(6),
      memory: (Math.random() * 100).toFixed(2),
      timestamp: Date.now().toString(),
    }
  }
  @Post('/podMetrics/:agentId')
  postPodMetrics(@Body() body: any) {
    return ResponseUtil.success(this.setPodMetrics(), '查询成功');
  }

  // 获取pod当前yaml
  public podYaml: any = {
    apiVersion: 'v1',
    kind: 'Pod',
    metadata: {
      annotations: null,
      clusterName: null,
      creationTimestamp: '2025-08-25T17:08:11+08:00',
      deletionGracePeriodSeconds: null,
      deletionTimestamp: null,
      finalizers: null,
      generateName: 'karmada-apiserver-56d6cfc4c8-',
      generation: null,
      labels: {
        app: 'karmada-apiserver',
        'pod-template-hash': '56d6cfc4c8',
      },
      managedFields: [
        {
          apiVersion: 'v1',
          fieldsType: 'FieldsV1',
          fieldsV1: {
            'f:metadata': {
              'f:generateName': {},
              'f:labels': {
                '.': {},
                'f:app': {},
                'f:pod-template-hash': {},
              },
              'f:ownerReferences': {
                '.': {},
                'k:{"uid":"ce3bbcdb-f397-4665-986f-3f9313453667"}': {},
              },
            },
            'f:spec': {
              'f:affinity': {
                '.': {},
                'f:podAntiAffinity': {
                  '.': {},
                  'f:requiredDuringSchedulingIgnoredDuringExecution': {},
                },
              },
              'f:automountServiceAccountToken': {},
              'f:containers': {
                'k:{"name":"karmada-apiserver"}': {
                  '.': {},
                  'f:command': {},
                  'f:image': {},
                  'f:imagePullPolicy': {},
                  'f:livenessProbe': {
                    '.': {},
                    'f:failureThreshold': {},
                    'f:httpGet': {
                      '.': {},
                      'f:path': {},
                      'f:port': {},
                      'f:scheme': {},
                    },
                    'f:initialDelaySeconds': {},
                    'f:periodSeconds': {},
                    'f:successThreshold': {},
                    'f:timeoutSeconds': {},
                  },
                  'f:name': {},
                  'f:ports': {
                    '.': {},
                    'k:{"containerPort":5443,"protocol":"TCP"}': {
                      '.': {},
                      'f:containerPort': {},
                      'f:name': {},
                      'f:protocol': {},
                    },
                  },
                  'f:readinessProbe': {
                    '.': {},
                    'f:failureThreshold': {},
                    'f:httpGet': {
                      '.': {},
                      'f:path': {},
                      'f:port': {},
                      'f:scheme': {},
                    },
                    'f:periodSeconds': {},
                    'f:successThreshold': {},
                    'f:timeoutSeconds': {},
                  },
                  'f:resources': {},
                  'f:terminationMessagePath': {},
                  'f:terminationMessagePolicy': {},
                  'f:volumeMounts': {
                    '.': {},
                    'k:{"mountPath":"/etc/karmada/pki"}': {
                      '.': {},
                      'f:mountPath': {},
                      'f:name': {},
                      'f:readOnly': {},
                    },
                  },
                },
              },
              'f:dnsPolicy': {},
              'f:enableServiceLinks': {},
              'f:restartPolicy': {},
              'f:schedulerName': {},
              'f:securityContext': {},
              'f:terminationGracePeriodSeconds': {},
              'f:tolerations': {},
              'f:volumes': {
                '.': {},
                'k:{"name":"karmada-cert"}': {
                  '.': {},
                  'f:name': {},
                  'f:secret': {
                    '.': {},
                    'f:defaultMode': {},
                    'f:secretName': {},
                  },
                },
              },
            },
          },
          manager: 'k3s',
          operation: 'Update',
          subresource: null,
          time: '2025-08-25T17:08:11+08:00',
        },
        {
          apiVersion: 'v1',
          fieldsType: 'FieldsV1',
          fieldsV1: {
            'f:status': {
              'f:conditions': {
                'k:{"type":"ContainersReady"}': {
                  '.': {},
                  'f:lastProbeTime': {},
                  'f:lastTransitionTime': {},
                  'f:status': {},
                  'f:type': {},
                },
                'k:{"type":"Initialized"}': {
                  '.': {},
                  'f:lastProbeTime': {},
                  'f:lastTransitionTime': {},
                  'f:status': {},
                  'f:type': {},
                },
                'k:{"type":"Ready"}': {
                  '.': {},
                  'f:lastProbeTime': {},
                  'f:lastTransitionTime': {},
                  'f:status': {},
                  'f:type': {},
                },
              },
              'f:containerStatuses': {},
              'f:hostIP': {},
              'f:phase': {},
              'f:podIP': {},
              'f:podIPs': {
                '.': {},
                'k:{"ip":"10.240.0.47"}': {
                  '.': {},
                  'f:ip': {},
                },
              },
              'f:startTime': {},
            },
          },
          manager: 'k3s',
          operation: 'Update',
          subresource: 'status',
          time: '2025-08-29T16:51:43+08:00',
        },
      ],
      name: 'karmada-apiserver-56d6cfc4c8-j49cx',
      namespace: 'karmada-system',
      ownerReferences: [
        {
          apiVersion: 'apps/v1',
          blockOwnerDeletion: true,
          controller: true,
          kind: 'ReplicaSet',
          name: 'karmada-apiserver-56d6cfc4c8',
          uid: 'ce3bbcdb-f397-4665-986f-3f9313453667',
        },
      ],
      resourceVersion: '74448',
      selfLink: null,
      uid: 'bd7f4846-54de-4bcb-8f1e-319f6a20636a',
    },
    spec: {
      activeDeadlineSeconds: null,
      affinity: {
        nodeAffinity: null,
        podAffinity: null,
        podAntiAffinity: {
          preferredDuringSchedulingIgnoredDuringExecution: null,
          requiredDuringSchedulingIgnoredDuringExecution: [
            {
              labelSelector: {
                matchExpressions: [
                  {
                    key: 'app',
                    operator: 'In',
                    values: ['karmada-apiserver'],
                  },
                ],
                matchLabels: null,
              },
              namespaceSelector: null,
              namespaces: null,
              topologyKey: 'kubernetes.io/hostname',
            },
          ],
        },
      },
      automountServiceAccountToken: false,
      containers: [
        {
          args: null,
          command: [
            'kube-apiserver',
            '--allow-privileged=true',
            '--authorization-mode=Node,RBAC',
            '--client-ca-file=/etc/karmada/pki/ca.crt',
            '--enable-bootstrap-token-auth=true',
            '--etcd-cafile=/etc/karmada/pki/etcd-ca.crt',
            '--etcd-certfile=/etc/karmada/pki/etcd-client.crt',
            '--etcd-keyfile=/etc/karmada/pki/etcd-client.key',
            '--etcd-servers=https://etcd-0.etcd.karmada-system.svc.cluster.local:2379',
            '--bind-address=0.0.0.0',
            '--kubelet-client-certificate=/etc/karmada/pki/karmada.crt',
            '--kubelet-client-key=/etc/karmada/pki/karmada.key',
            '--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname',
            '--disable-admission-plugins=StorageObjectInUseProtection,ServiceAccount',
            '--runtime-config=',
            '--apiserver-count=1',
            '--secure-port=5443',
            '--service-account-issuer=https://kubernetes.default.svc.cluster.local',
            '--service-account-key-file=/etc/karmada/pki/karmada.key',
            '--service-account-signing-key-file=/etc/karmada/pki/karmada.key',
            '--service-cluster-ip-range=10.96.0.0/12',
            '--proxy-client-cert-file=/etc/karmada/pki/front-proxy-client.crt',
            '--proxy-client-key-file=/etc/karmada/pki/front-proxy-client.key',
            '--requestheader-allowed-names=front-proxy-client',
            '--requestheader-client-ca-file=/etc/karmada/pki/front-proxy-ca.crt',
            '--requestheader-extra-headers-prefix=X-Remote-Extra-',
            '--requestheader-group-headers=X-Remote-Group',
            '--requestheader-username-headers=X-Remote-User',
            '--tls-cert-file=/etc/karmada/pki/apiserver.crt',
            '--tls-private-key-file=/etc/karmada/pki/apiserver.key',
            '--tls-min-version=VersionTLS13',
          ],
          env: null,
          envFrom: null,
          image: 'registry.k8s.io/kube-apiserver:v1.25.4',
          imagePullPolicy: 'IfNotPresent',
          lifecycle: null,
          livenessProbe: {
            exec: null,
            failureThreshold: 3,
            grpc: null,
            httpGet: {
              host: null,
              httpHeaders: null,
              path: '/livez',
              port: 5443,
              scheme: 'HTTPS',
            },
            initialDelaySeconds: 15,
            periodSeconds: 30,
            successThreshold: 1,
            tcpSocket: null,
            terminationGracePeriodSeconds: null,
            timeoutSeconds: 5,
          },
          name: 'karmada-apiserver',
          ports: [
            {
              containerPort: 5443,
              hostIP: null,
              hostPort: null,
              name: 'server',
              protocol: 'TCP',
            },
          ],
          readinessProbe: {
            exec: null,
            failureThreshold: 3,
            grpc: null,
            httpGet: {
              host: null,
              httpHeaders: null,
              path: '/readyz',
              port: 5443,
              scheme: 'HTTPS',
            },
            initialDelaySeconds: null,
            periodSeconds: 30,
            successThreshold: 1,
            tcpSocket: null,
            terminationGracePeriodSeconds: null,
            timeoutSeconds: 5,
          },
          resources: {
            limits: null,
            requests: null,
          },
          securityContext: null,
          startupProbe: null,
          stdin: null,
          stdinOnce: null,
          terminationMessagePath: '/dev/termination-log',
          terminationMessagePolicy: 'File',
          tty: null,
          volumeDevices: null,
          volumeMounts: [
            {
              mountPath: '/etc/karmada/pki',
              mountPropagation: null,
              name: 'karmada-cert',
              readOnly: true,
              subPath: null,
              subPathExpr: null,
            },
          ],
          workingDir: null,
        },
      ],
      dnsConfig: null,
      dnsPolicy: 'ClusterFirst',
      enableServiceLinks: true,
      ephemeralContainers: null,
      hostAliases: null,
      hostIPC: null,
      hostNetwork: null,
      hostPID: null,
      hostname: null,
      imagePullSecrets: null,
      initContainers: null,
      nodeName: 'federation02',
      nodeSelector: null,
      os: null,
      overhead: null,
      preemptionPolicy: 'PreemptLowerPriority',
      priority: 0,
      priorityClassName: null,
      readinessGates: null,
      restartPolicy: 'Always',
      runtimeClassName: null,
      schedulerName: 'default-scheduler',
      securityContext: {
        fsGroup: null,
        fsGroupChangePolicy: null,
        runAsGroup: null,
        runAsNonRoot: null,
        runAsUser: null,
        seLinuxOptions: null,
        seccompProfile: null,
        supplementalGroups: null,
        sysctls: null,
        windowsOptions: null,
      },
      serviceAccount: 'default',
      serviceAccountName: 'default',
      setHostnameAsFQDN: null,
      shareProcessNamespace: null,
      subdomain: null,
      terminationGracePeriodSeconds: '30',
      tolerations: [
        {
          effect: 'NoExecute',
          key: null,
          operator: 'Exists',
          tolerationSeconds: null,
          value: null,
        },
      ],
      topologySpreadConstraints: null,
      volumes: [
        {
          awsElasticBlockStore: null,
          azureDisk: null,
          azureFile: null,
          cephfs: null,
          cinder: null,
          configMap: null,
          csi: null,
          downwardAPI: null,
          emptyDir: null,
          ephemeral: null,
          fc: null,
          flexVolume: null,
          flocker: null,
          gcePersistentDisk: null,
          gitRepo: null,
          glusterfs: null,
          hostPath: null,
          iscsi: null,
          name: 'karmada-cert',
          nfs: null,
          persistentVolumeClaim: null,
          photonPersistentDisk: null,
          portworxVolume: null,
          projected: null,
          quobyte: null,
          rbd: null,
          scaleIO: null,
          secret: {
            defaultMode: 420,
            items: null,
            optional: null,
            secretName: 'karmada-cert',
          },
          storageos: null,
          vsphereVolume: null,
        },
      ],
    },
    status: {
      conditions: [
        {
          lastProbeTime: null,
          lastTransitionTime: '2025-08-25T17:08:11+08:00',
          message: null,
          reason: null,
          status: 'True',
          type: 'Initialized',
        },
        {
          lastProbeTime: null,
          lastTransitionTime: '2025-08-29T16:51:43+08:00',
          message: null,
          reason: null,
          status: 'True',
          type: 'Ready',
        },
        {
          lastProbeTime: null,
          lastTransitionTime: '2025-08-29T16:51:43+08:00',
          message: null,
          reason: null,
          status: 'True',
          type: 'ContainersReady',
        },
        {
          lastProbeTime: null,
          lastTransitionTime: '2025-08-25T17:08:11+08:00',
          message: null,
          reason: null,
          status: 'True',
          type: 'PodScheduled',
        },
      ],
      containerStatuses: [
        {
          containerID:
            'iSulad://487d6de5804b25205ad26c9cfbfc06ca86612b31cad71a6c7e43af4e5c310fdf',
          image:
            '8e49cdf98f4d1bb02b6ffdd753e549173bba453d3d476f03034be2ff8b928f43',
          imageID:
            'docker-pullable://registry.k8s.io/kube-apiserver@sha256:07462a1014528c044e35fc84b3a1715db5dfd9f68a07f4cb2c81ebeb5b064c43',
          lastState: {
            running: null,
            terminated: {
              containerID:
                'iSulad://f1724f38f29634b40a19e26a919ca7113173fb6ad8e4e1913e4466d70ef2a63a',
              exitCode: 255,
              finishedAt: '2025-08-29T16:50:21+08:00',
              message: null,
              reason: 'Error',
              signal: null,
              startedAt: '2025-08-29T15:49:05+08:00',
            },
            waiting: null,
          },
          name: 'karmada-apiserver',
          ready: true,
          restartCount: 10,
          started: true,
          state: {
            running: {
              startedAt: '2025-08-29T16:51:12+08:00',
            },
            terminated: null,
            waiting: null,
          },
        },
      ],
      ephemeralContainerStatuses: null,
      hostIP: '192.168.8.30',
      initContainerStatuses: null,
      message: null,
      nominatedNodeName: null,
      phase: 'Running',
      podIP: '10.240.0.47',
      podIPs: [
        {
          ip: '10.240.0.47',
        },
      ],
      qosClass: 'BestEffort',
      reason: null,
      startTime: '2025-08-25T17:08:11+08:00',
    },
  };
  @Post('/getPod/:agentId')
  postPodYaml(@Body() body: any) {
    return ResponseUtil.success(this.podYaml, '查询成功');
  }


  /* 删除当前pod */
  @Post('/deletePod/:agentId')
  postDeletePod(@Body() body: any) {
    return this.NodeService.postDeletePod(body.name);
  }
}
